package com.tianma315.admin.produce.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tianma315.admin.common.base.CoreServiceImpl;
import com.tianma315.admin.common.exception.MessageException;
import com.tianma315.admin.invocie.domain.InvoiceProduct;
import com.tianma315.admin.invocie.domain.dto.ProductForm;
import com.tianma315.admin.marshalling.domain.MarshallingDO;
import com.tianma315.admin.marshalling.service.MarshallingService;
import com.tianma315.admin.material.VO.MaterialVO;
import com.tianma315.admin.material.dao.MaterialDao;
import com.tianma315.admin.material.domain.MaterialDO;
import com.tianma315.admin.material.domain.PurchaseDO;
import com.tianma315.admin.material.service.MaterialService;
import com.tianma315.admin.material.service.PurchaseService;
import com.tianma315.admin.produce.VO.ScAdditiveVO;
import com.tianma315.admin.produce.dao.AdditiveMaterialDao;
import com.tianma315.admin.produce.domain.AdditiveMaterialDO;
import com.tianma315.admin.produce.dto.MaterialForm;
import com.tianma315.admin.produce.dto.ScAdditiveDto;
import com.tianma315.admin.product.domain.Product;
import com.tianma315.admin.stock.domain.Stock;
import com.tianma315.admin.supplier.domain.SupplierDO;
import com.tianma315.admin.util.CellUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tianma315.admin.produce.dao.ScAdditiveDao;
import com.tianma315.admin.produce.domain.ScAdditiveDO;
import com.tianma315.admin.produce.service.ScAdditiveService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 配添加剂(生产)
 * </pre>
 * <small> 2019-05-30 09:53:17 | Aron</small>
 */
@Service
@Transactional
public class ScAdditiveServiceImpl extends CoreServiceImpl<ScAdditiveDao, ScAdditiveDO> implements ScAdditiveService {

    @Autowired
    private ScAdditiveDao scAdditiveDao;

    @Autowired
    private AdditiveMaterialDao additiveMaterialDao;

    @Autowired
    private MaterialService materialService;

//    @Autowired
//    private PurchaseService purchaseService;

//    @Autowired
//    private MarshallingService marshallingService;

    @Override
    public void importAdditive(MultipartFile file, Long userId) {
        Boolean flag = CellUtil.isExcel(file.getOriginalFilename());
        if (!flag){
            throw new MessageException("只支持Excel文件");
        }

//        Wrapper<PurchaseDO> wrapper = new EntityWrapper<>();
//        wrapper.eq("state",0);
//        List<PurchaseDO> purchaseDOList = purchaseService.selectList(wrapper);
        List<MaterialDO> materialDOList = materialService.getMaterialList();
        //List<MarshallingDO> marshallingList = marshallingService.getMarshallingList();

        try {
            HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
            Sheet sheet = wb.getSheetAt(0);
            int rowNum = sheet.getLastRowNum(); //返回行数下标 从0开始
            //判断原材料项是否有重复值
            List<String> materialList = new ArrayList<>();
            for (int i = 2; i <= rowNum; i++) {
                Row rows = sheet.getRow(i);
                Cell materialCell = rows.getCell(4);
                materialList.add(materialCell.getStringCellValue());
            }
            Set<String> set = new HashSet<>(materialList);
            if (materialList.size()!=set.size()){
                throw new MessageException("原料不能重复");
            }

            //前两行都不是内容，所以从2开始
            Row row = sheet.getRow(2);
//            short num = row.getLastCellNum();
            //添加剂数据导入
            ScAdditiveDO scAdditiveDO = new ScAdditiveDO();
            scAdditiveDO.setState(0);
            scAdditiveDO.setCreateBy(userId);
            scAdditiveDO.setCreateDate(Calendar.getInstance().getTime());

//            Cell purchaseIdCell = row.getCell(0);
//            if (CellUtil.isCellEmpty(purchaseIdCell)){
//                    throw new MessageException("原料进库批次号不能为空");
//                }
//            List<PurchaseDO> purchaseFilterResult = purchaseDOList.stream()
//                        .filter(item -> item.getPurchaseNo().equals(purchaseIdCell.getStringCellValue()))
//                        .collect(Collectors.toList());
//            scAdditiveDO.setPurchaseId(purchaseFilterResult.get(0).getPurchaseId());

//            Cell marshallingIdCell = row.getCell(1);
//            if (CellUtil.isCellEmpty(marshallingIdCell)){
//                throw new MessageException("班组项不能为空");
//            }
//            List<MarshallingDO> marshallingFilterResult = marshallingList.stream()
//                    .filter(item -> item.getMarshallingName().equals(marshallingIdCell.getStringCellValue()))
//                    .collect(Collectors.toList());
//            scAdditiveDO.setMarshallingId(marshallingFilterResult.get(0).getMarshallingId());

            Cell weighingByCell = row.getCell(0);
            if (CellUtil.isCellEmpty(weighingByCell)){
                throw new MessageException("秤量人不能为空");
            }
            scAdditiveDO.setWeighingBy(weighingByCell.getStringCellValue());

            Cell checkByCell = row.getCell(1);
            if (CellUtil.isCellEmpty(checkByCell)){
                throw new MessageException("复核人不能为空");
            }
            scAdditiveDO.setCheckBy(checkByCell.getStringCellValue());

            Cell additiveDateCell = row.getCell(2);
                if (additiveDateCell==null){
                    throw new MessageException("配添加剂日期不能为空");
                }
            scAdditiveDO.setAdditiveDate(additiveDateCell.getDateCellValue());

            Cell produceTaskIdCell = row.getCell(3);
            if (CellUtil.isCellEmpty(produceTaskIdCell)){
                throw new MessageException("任务id不能为空");
            }
            scAdditiveDO.setProduceTaskId(Integer.parseInt(produceTaskIdCell.getStringCellValue()));
                insert(scAdditiveDO);
         //添加剂原材料绑定数据导入
            for (int i = 2; i <= rowNum; i++) {
                Row rows = sheet.getRow(i);
                AdditiveMaterialDO additiveMaterialDO = new AdditiveMaterialDO();
                additiveMaterialDO.setAdditiveId(scAdditiveDO.getAdditiveId().longValue());

                Cell materialCell = rows.getCell(4);
                if (CellUtil.isCellEmpty(materialCell)){
                    throw new MessageException("原材料不能为空");
                }
                List<MaterialDO> materialFilterResult = materialDOList.stream()
                        .filter(item -> item.getMaterialName().equals(materialCell.getStringCellValue()))
                        .collect(Collectors.toList());
                additiveMaterialDO.setMaterialId(materialFilterResult.get(0).getMaterialId().longValue());

                Cell materialSizeCell = rows.getCell(5);
                if (CellUtil.isCellEmpty(materialSizeCell)){
                    throw new MessageException("原材料数量不能为空");
                }
                additiveMaterialDO.setMaterialSize(Double.parseDouble(materialSizeCell.getStringCellValue()));
                Cell batchCell = rows.getCell(6);
                if (CellUtil.isCellEmpty(batchCell)){
                    throw new MessageException("原材料批次号不能为空");
                }
                additiveMaterialDO.setBatch(batchCell.getStringCellValue());
                if (additiveMaterialDao.insert(additiveMaterialDO) != 1)
                    throw new MessageException("添加剂原材料绑定失败");
            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public ScAdditiveVO selectVOById(Integer additiveId) {
        ScAdditiveVO scAdditiveVO= scAdditiveDao.selectVOById(additiveId);
        return scAdditiveVO;
    }

    @Override
    public void updateDtoById(ScAdditiveDto scAdditive) {
        scAdditiveDao.updateById(scAdditive);
        //删除关联数据，再添加更新数据
        Wrapper<AdditiveMaterialDO> wrapper = new EntityWrapper<>();
        wrapper.eq("additive_id",scAdditive.getAdditiveId());
        additiveMaterialDao.delete(wrapper);

        for (AdditiveMaterialDO mat : scAdditive.getMaterials()) {
            mat.setAdditiveId(scAdditive.getAdditiveId().longValue());
            if (additiveMaterialDao.insert(mat) != 1)
                throw new MessageException("原材料修改失败");
        }
    }

    @Override
    public Page<ScAdditiveVO> getScAdditiveVO(Integer pageNumber, Integer pageSize, ScAdditiveDO scAdditiveDTO) {
        Page<ScAdditiveVO> scAdditiveVOPage = new Page<>(pageNumber,pageSize);
        List<ScAdditiveVO> scAdditiveVOList = scAdditiveDao.getScAdditiveVOPage(scAdditiveDTO.getProduceTaskId());
        scAdditiveVOPage.setRecords(scAdditiveVOList);
        return scAdditiveVOPage;
    }

    @Override
    public Boolean addScAdditiveDO(ScAdditiveDto scAdditiveDto) {
//        scAdditiveDto.setState(0);
        ScAdditiveDO scAdditiveDO = new ScAdditiveDO();
        BeanUtils.copyProperties(scAdditiveDto,scAdditiveDO);
        scAdditiveDO.setState(0);
        if (!insert(scAdditiveDO))
            throw new MessageException("添加剂单创建失败");

        for (AdditiveMaterialDO mat : scAdditiveDto.getMaterials()) {
            //添加原材料
//            AdditiveMaterialDO additiveMaterialDO = new AdditiveMaterialDO();
//            additiveMaterialDO.setAdditiveId(scAdditiveDO.getAdditiveId().longValue());
//            additiveMaterialDO.setMaterialId(mat.getMaterialId());
//            additiveMaterialDO.setMaterialSize(mat.getMaterialSize());
//            additiveMaterialDO.setBatch(mat.getBatch());
            System.out.println("==============="+mat.getMaterialSize());
            mat.setAdditiveId(scAdditiveDO.getAdditiveId().longValue());
            if (additiveMaterialDao.insert(mat) != 1)
                throw new MessageException("原材料绑定失败");
        }
        return true;
    }

    @Override
    public Boolean deleteScAdditiveDO(Integer id) {
        ScAdditiveDO scAdditiveDO = new ScAdditiveDO();
        scAdditiveDO.setState(1);
        scAdditiveDO.setAdditiveId(id);
        return updateById(scAdditiveDO);
    }

    @Override
    public List<ScAdditiveDO> getScAdditiveDO(Integer produceTaskId) {
        Wrapper<ScAdditiveDO> wrapper = new EntityWrapper<>();
        wrapper.eq("state",0);
        wrapper.eq("produce_task_id",produceTaskId);
        List<ScAdditiveDO> scAdditiveDOList = selectList(wrapper);
        return scAdditiveDOList;
    }

    @Override
    public HSSFWorkbook exportAdditive(Integer produceTaskId) {
        String[] title = {"称量人","复核人","配添加剂时间(2020/1/1)","生成任务id(不可编辑)","原材料名称","原材料数量","原材料批次号"};
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("添加剂记录模板");

//        sheet.addMergedRegion(new CellRangeAddress(0,0,0,8));//第一行第一列开始，跨8列
        HSSFRow titleRow = sheet.createRow(0);//第0行

        //标题样式
        HSSFCellStyle titleStyle = wb.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short)18);
        titleStyle.setFont(font);

        //生成标题
        HSSFCell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("添加剂记录模板（前4项选项只需填写一行）");
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
        titleCell.setCellStyle(titleStyle);

        //红色字体
        HSSFCellStyle redStyle = wb.createCellStyle();
        redStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont redFont = wb.createFont();
        redFont.setBold(true);
        redFont.setColor(Font.COLOR_RED);
        redStyle.setFont(redFont);

        //默认字体样式
        HSSFCellStyle defaultStyle = wb.createCellStyle();
        defaultStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont defaultFont = wb.createFont();
        defaultFont.setBold(true);
        defaultStyle.setFont(defaultFont);


        //声明列对象
        HSSFCell cell = null;
        //创建表头
        HSSFRow headRow = sheet.createRow(1);
        for(int i=0;i<title.length;i++){
            //下标为0,2,3,4是必填列
                cell = headRow.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(redStyle);
        }
        //设置生产任务id
        HSSFRow headRow1 = sheet.createRow(2);
        cell = headRow1.createCell(3);
        cell.setCellValue(produceTaskId);



        //设置原料进库批次号列表
//        Wrapper<PurchaseDO> wrapper = new EntityWrapper<>();
//        wrapper.eq("state",0);
//        List<PurchaseDO> purchaseDOList = purchaseService.selectList(wrapper);
//        List<String> purchaseNOList = purchaseDOList.stream().map(item -> item.getPurchaseNo()).collect(Collectors.toList());
//        String[] purchaseNOArr = purchaseNOList.toArray(new String[purchaseNOList.size()]);
//        //设置设备类型为下拉框选项
//        DVConstraint purchaseNOConstraint = DVConstraint.createExplicitListConstraint(purchaseNOArr);
//        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
//        CellRangeAddressList purchaseNORegions = new CellRangeAddressList(2,
//                2, 0, 0);
//        HSSFDataValidation purchaseNOData = new HSSFDataValidation(
//                purchaseNORegions, purchaseNOConstraint);
//        sheet.addValidationData(purchaseNOData);

        //生成班组列表
//        List<MarshallingDO> marshallingList = marshallingService.getMarshallingList();
//        List<String> marshallingNameList = marshallingList.stream().map(item -> item.getMarshallingName()).collect(Collectors.toList());
//        String[] marshallingNameArr = marshallingNameList.toArray(new String[marshallingNameList.size()]);
//
//        //设置设备类型为下拉框选项
//        DVConstraint marshallingConstraint = DVConstraint.createExplicitListConstraint(marshallingNameArr);
//        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
//        CellRangeAddressList marshallingRegions = new CellRangeAddressList(2,
//                2, 1, 1);
//        HSSFDataValidation marshallingData = new HSSFDataValidation(
//                marshallingRegions, marshallingConstraint);
//        sheet.addValidationData(marshallingData);

        //生成原料列表
        List<MaterialDO> materialDOS = materialService.getMaterialList();
        List<String> materialList = materialDOS.stream().map(item -> item.getMaterialName()).collect(Collectors.toList());
        String[] materialNameArr = materialList.toArray(new String[materialList.size()]);

        //设置设备类型为下拉框选项
        DVConstraint constraint = DVConstraint.createExplicitListConstraint(materialNameArr);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList regions = new CellRangeAddressList(2,
                10000, 4, 4);
        HSSFDataValidation materialData = new HSSFDataValidation(
                regions, constraint);
        sheet.addValidationData(materialData);


        return wb;
    }
}
